package String;

import java.math.BigDecimal;

public class _43_MultiplyStrings {
    //solution 1:using bigdecimal
    public String multiply0(String num1, String num2) {
        BigDecimal bd1 = new BigDecimal(num1);
        BigDecimal bd2 = new BigDecimal(num2);
        return bd1.multiply(bd2).toString();
    }

    //reference solution 2:use bit multiply and the multiply's method
    //hint 1:x bits * y bits, the result's max bits is x+y
    public String multiply(String num1, String num2) {
        int N1 = num1.length(), N2 = num2.length();
        int[] result = new int[N1 + N2];
        for (int i = N1-1; i>=0; i--) {
            for(int j = N2-1;j>=0;j--) {
                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int pos1 = i+j,pos2 = i+j+1;
                int sum = mul + result[pos2];
                result[pos1] += sum/10;
                result[pos2] = sum%10;
            }
        }
        StringBuffer sb = new StringBuffer();
        for (int i : result) {
            if (!(sb.length() == 0 && i == 0)) {
                sb.append(i);
            }
        }
        return sb.length() == 0 ? "0" : sb.toString();
    }
}
